import useCommonUtils from '@/utils/common'
const { formatDate } = useCommonUtils();

class Result {
  constructor(message, data = {}) {
    this.message = message
    this.data = data
  }
}

const getStorageItemById = id => {
  const res = uni.getStorageInfoSync();
  const filterList = res.keys.filter(key => key === `order-${id}`);
  return filterList[0] ? uni.getStorageSync(filterList[0]) : {}
}

const api = {
  add: (data) => {
    data.id = 'D' + new Date().getTime();
    data.createTime = formatDate(new Date(), 'dateTime')
    console.log('add', data);
    return new Promise((resolve) => {
      uni.setStorageSync(`order-${data.id}`, data);
      resolve(new Result('添加成功', data))
    })
  },
  delete: id => {
    return new Promise((resolve) => {
      uni.removeStorageSync(`order-${id}`)
      resolve(new Result('删除成功'))
    })
  },
  update: (data) => {
    if (!data.id) {
      console.error('订单update接口参数缺失id')
      return;
    }
    return new Promise((resolve) => {
      const item = getStorageItemById(data.id);
      uni.setStorageSync(`order-${data.id}`, Object.assign({}, item, data));
      resolve(new Result('修改成功', { id: data.id }))
    })
  },
  detail: id => {
    return new Promise((resolve) => {
      const item = getStorageItemById(id);
      resolve(new Result('查询成功', item))
    })
  },
  getCount: () => {
    return new Promise((resolve) => {
      const res = uni.getStorageInfoSync();
      const orderKeyList = res.keys.filter(key => key.indexOf('order-') !== -1);
      const statusList = [0, 0, 0, 0] //待付款 待使用 已完成 取消/退款
      const totalPrice = orderKeyList.reduce((pre, key) => {
        const item = uni.getStorageSync(key);
        switch (item.status) {
          case 0: statusList[0]++; break;
          case 1: statusList[1]++; break;
          case 2: statusList[2]++; break;
          default: statusList[3]++; break;
        }
        return pre + item.price;
      }, 0);
      resolve(new Result('查询成功', { totalPrice, totalCount: orderKeyList.length, statusList }))
    })
  },
  pageList: (data = { pageSize: 10, pageNum: 1 }) => {
    return new Promise((resolve) => {
      console.log('pageList data', data);
      const startIndex = (data.pageNum - 1) * data.pageSize;
      const res = uni.getStorageInfoSync();
      const orderList = res.keys.filter(key => key.indexOf('order-') !== -1).map(key => uni.getStorageSync(key));

      console.log('pageList orderList', orderList);

       // 提取data中非分页参数作为过滤条件
      const filterConditions = Object.entries(data).reduce((acc, [key, value]) => {
        if (key !== 'pageSize' && key !== 'pageNum') acc[key] = value;
        return acc;
      }, {});
      console.log('pageList filterConditions', filterConditions);

      // 根据条件过滤orderList，当每个条件需要满足多个值时，用数组传递
      const filterList = orderList.filter(item => {
        return Object.entries(filterConditions).every(([conditionKey, conditionValue]) => {
          console.log('pageList filterList', conditionKey, conditionValue);
          if (Array.isArray(conditionValue)) return conditionValue.includes(item[conditionKey]);
          else return item[conditionKey] === conditionValue;
        });
      });

      const totalCount = filterList.length;
      const totalPages = totalCount > 0 ? Math.ceil(totalCount / data.pageSize) : 0;
      const paginatedList = filterList.slice(startIndex, startIndex + data.pageSize);
      
      resolve(new Result('查询成功', { totalCount, totalPages, list: paginatedList}));
    })
  }
}

export default api
